namespace Example.Web
{
    using System;
    using System.Xml;
    using System.Xml.Serialization;
    using SimpleWebServices.Web.UI.Html;
    using SimpleWebServices.Web.UI.Html.Elements;

    [XmlRoot("fieldset")]
    public sealed class ExampleChoice : RadioFieldset, IXmlSerializable
    {
        public ExampleChoice()
            : base("choice", ExampleChoice.Legend)
        {
            this.Elements.Add(ExampleChoice.Choice(1));
            this.Elements.Add(ExampleChoice.Choice(2));
        }

        private static Legend Legend
        {
            get
            {
                Legend value = new Legend
                {
                    Id = "legend-choice",
                    Elements =
                    {
                        new AsterixSpan(),
                        new TextString("Please choose one of the following")
                    }
                };

                return value;
            }
        }

        public override IElement Deserialize(string name, string type, string xml)
        {
            IElement result = null;

            if ("fieldset".Equals(name, StringComparison.OrdinalIgnoreCase))
            {
                if ("example-choice".Equals(type, StringComparison.OrdinalIgnoreCase))
                {
                    result = new ExampleChoice();
                }
            }

            return result;
        }

        private static IElement Choice(int index)
        {
            Paragraph result = new Paragraph();
            result.Elements.Add(ExampleChoice.ChoiceInput(index));
            result.Elements.Add(ExampleChoice.ChoiceLabel(index));

            return result;
        }

        private static RadioInput ChoiceInput(int index)
        {
            string value = XmlConvert.ToString(index);
            return new RadioInput
            {
                Id = "choice:" + value,
                Name = "choice",
                Value = value,
                Suppress = true,
                Title = string.Concat("This is choice number ", value, ".")
            };
        }

        private static Label ChoiceLabel(int index)
        {
            string value = XmlConvert.ToString(index);
            Label result = new Label
            {
                Id = "label-choice:" + value,
                For = "choice:" + value,
                Title = string.Concat("This is choice number ", value, "."),
                Elements =
                {
                    new TextString(string.Concat("This is choice number ", value, "."))
                }
            };

            return result;
        }
    }
}